var express = require('express');
var fs=require('fs');
var path=require('path');
var app = express();
var mime = require('mime');
// app.get('/', function (req, res) {
//   res.send('Hello World!');
// });

// app.use(express.static('E:/html'))

//变更Node.js进程的当前工作目录
process.chdir('E:/html/express/localserver/')

var baseUrl;
app.use(function(req,res){
  var rurl=req.url;
  var staticurl;
  if(rurl==='/'){
    res.send('当前服务基于E:/html目录。')
    return;
  }
  if(rurl.indexOf('index.html')!==-1){
    baseUrl=path.resolve('E:','../..'+rurl)
    staticurl=baseUrl;
    baseUrl=baseUrl.replace('index.html','');
    console.log('根据index.html得到的根目录是：',baseUrl,'后续资源加载依赖此目录(>^ω^<)');
  }else{
    staticurl=path.resolve(baseUrl||'E://html','.'+req.url);
  }
  //调整输出类型
  var fileExtension = rurl.substring(rurl.lastIndexOf('.') + 1);
  res.type(mime.getType(fileExtension))
  res.send(fs.readFileSync(staticurl))
})

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', 'localhost', port);
});